
package com.contactportal.tags;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

public class SecurityCheckValidate extends SimpleTagSupport {

    @Override
    public void doTag() throws JspException {
        JspWriter out = getJspContext().getOut();
        PageContext context = (PageContext) getJspContext();
        HttpSession session = context.getSession();
        try {
              
            ServletRequest request = context.getRequest();
            String remoteAddr = request.getRemoteAddr();
            ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
            reCaptcha.setPrivateKey("6LcqNsoSAAAAAKlfg9WHv2kJkEwtwLBL6M_LIqyZ");

            String challenge = request.getParameter("recaptcha_challenge_field");
            String uresponse = request.getParameter("recaptcha_response_field");
            ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

            if (reCaptchaResponse.isValid()) {
                try {
                    session.setAttribute("msg","valid");
                    context.forward("login.jsp");
                } catch (ServletException ex) {
                    Logger.getLogger(SecurityCheckValidate.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else
            {
                try {
                    
                    session.setAttribute("msg", "invalid");
                    context.forward("register.jsp");
                } catch (ServletException ex) {
                    Logger.getLogger(SecurityCheckValidate.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (java.io.IOException ex) {
            throw new JspException("Error in SecurityCheckValidate tag", ex);
        }
    }
}
